package com.javajun.endofterm.controller.api_v1;

import com.javajun.endofterm.common.AjaxUtils;
import com.javajun.endofterm.entity.SysUser;
import com.javajun.endofterm.service.SysUserService;
import com.javajun.endofterm.web.form.SysUserFoem;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Xiong Limin
 * Date: 2020-12-06-9:55 下午
 */
@RequestMapping(value = "/api-v1/sysUser")
@RestController
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping(value = "/update-password")
    public Object passwordUpdate(String oldPassword, String newPassword, String againPassword) {
        SysUser loadSysUser = sysUserService.getLoadSysUser();
        boolean matches = new BCryptPasswordEncoder().matches(oldPassword, loadSysUser.getPassword());
        boolean equals = newPassword.equals(againPassword);
        if (!matches) {
            return AjaxUtils.buildFailResult("原密码错误");
        }
        if (!equals) {
            return AjaxUtils.buildFailResult("两次输入密码不一致");
        }
        loadSysUser.setPassword(new BCryptPasswordEncoder().encode(newPassword));
        sysUserService.save(loadSysUser);
        return AjaxUtils.buildResult("修改密码成功");
    }

    @RequestMapping(value = "/update-info")
    public Object infoUpdate(@RequestBody SysUserFoem form) {
        SysUser loadSysUser = sysUserService.getLoadSysUser();
        BeanUtils.copyProperties(form, loadSysUser, "username");
        sysUserService.save(loadSysUser);
        return AjaxUtils.buildResult("修改信息成功");
    }
}
